package com.ms.service.module.fish.test;

import java.net.InetSocketAddress;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

import com.ms.service.module.fish.message.FishManualCodec;
import com.ms.service.module.fish.message.IWrite;
import com.xpec.c4.message.MessageTypes;
import com.xpec.c4.service.common.ModuleInfo;
import com.xpec.c4.service.message.NetMessage;
import com.xpec.c4.service.module.ModuleName;

public class FishClient {

	private String ip;
	private int port;
	private ClientBootstrap mBootstrap;
	
	public FishClient(String ip, int port) {
		this.ip = ip;
		this.port = port;
	}

	public void connect() throws InterruptedException {
		mBootstrap = new ClientBootstrap(new NioClientSocketChannelFactory());
		mBootstrap.setPipelineFactory( new ChannelPipelineFactory() {
			@Override
			public ChannelPipeline getPipeline() throws Exception {
				ChannelPipeline p = Channels.pipeline();

				p.addLast(XSENetNettyDecoder.class.getSimpleName(), new XSENetNettyDecoder());
				p.addLast(XSENetNettyEncoder.class.getSimpleName(), new XSENetNettyEncoder());
				/// 處理我們自己訊息的一定是最後一個 addLast 的
				p.addLast(FishClientHandler.class.getSimpleName(), new FishClientHandler());
				
				return p;	
			}
		});
		try {
			mBootstrap.connect(new InetSocketAddress(ip, port)).sync().getChannel().getCloseFuture().sync();
		} finally {
			mBootstrap.shutdown();
		}
	}
	
	public static void sendMsg(ChannelHandlerContext ctx,IWrite message){
		FishManualCodec data = new FishManualCodec(message);
		NetMessage netMessage = new NetMessage(MessageTypes.C_FISH_ACTION_DISPATCH, data);
		netMessage.setModuleID(ModuleName.FISH_GAME);
		ctx.getChannel().write(netMessage);
	}

}
